<?php

namespace app\adminapi\controller;

use app\model\CategoryModel;
use Respect\Validation\Exceptions\ValidationException;
use Respect\Validation\Validator as v;
use Webman\Http\Request;

class Category extends BaseAdminApi
{
    protected $dataModel = CategoryModel::class;
    protected array $allowSearch = ['name', 'description', 'status', 'parent_id'];

    /**
     * 获取类目详情
     */
    public function getCategoryDetail(Request $request)
    {
        try {
            $params = v::input($request->get(), [
                'id' => v::stringType()->notEmpty()->setName('类目ID'),
            ]);
        } catch (ValidationException $e) {
            return $this->fail($e->getMessage());
        }

        try {
            $category = CategoryModel::find($params['id']);
            
            if (!$category) {
                return $this->fail('类目不存在');
            }

            return $this->success('获取类目详情成功', $category);
        } catch (\Exception $e) {
            return $this->fail('获取类目详情失败：' . $e->getMessage());
        }
    }

    /**
     * 创建类目
     */
    public function createCategory(Request $request)
    {
        $data = $request->post();
        
        // 验证必填字段
        if (empty($data['name'])) {
            return $this->fail('类目名称不能为空');
        }

        // 验证类目名称长度
        if (mb_strlen($data['name']) > 50) {
            return $this->fail('类目名称不能超过50个字符');
        }

        // 检查类目名称是否已存在
        $existCategory = CategoryModel::where('name', $data['name'])->first();
        if ($existCategory) {
            return $this->fail('类目名称已存在');
        }

        try {
            $category = new CategoryModel();
            $category->name = $data['name'];
            
            $category->save();

            return $this->success('创建类目成功', $category);
        } catch (\Exception $e) {
            return $this->fail('创建类目失败：' . $e->getMessage());
        }
    }

    /**
     * 更新类目
     */
    public function updateCategory(Request $request)
    {
        $data = $request->post();
        
        if (empty($data['id'])) {
            return $this->fail('类目ID不能为空');
        }

        if (empty($data['name'])) {
            return $this->fail('类目名称不能为空');
        }

        // 验证类目名称长度
        if (mb_strlen($data['name']) > 50) {
            return $this->fail('类目名称不能超过50个字符');
        }

        try {
            $category = CategoryModel::find($data['id']);
            
            if (!$category) {
                return $this->fail('类目不存在');
            }

            // 检查类目名称是否已被其他类目使用
            $existCategory = CategoryModel::where('name', $data['name'])
                ->where('id', '!=', $data['id'])
                ->first();
            if ($existCategory) {
                return $this->fail('类目名称已存在');
            }

            $category->name = $data['name'];
            $category->updated_at = date('Y-m-d H:i:s');
            
            $category->save();

            return $this->success('更新类目成功', $category);
        } catch (\Exception $e) {
            return $this->fail('更新类目失败：' . $e->getMessage());
        }
    }

    /**
     * 删除类目
     */
    public function deleteCategory(Request $request)
    {
        $data = $request->post();
        
        if (empty($data['id'])) {
            return $this->fail('类目ID不能为空');
        }

        try {
            $category = CategoryModel::find($data['id']);
            
            if (!$category) {
                return $this->fail('类目不存在');
            }

            // 这里可以添加检查是否有圈子使用了这个类目
            // 如果有使用，可以选择禁止删除或者提示用户
            
            $category->delete();

            return $this->success('删除类目成功');
        } catch (\Exception $e) {
            return $this->fail('删除类目失败：' . $e->getMessage());
        }
    }

    /**
     * 批量删除类目
     */
    public function batchDeleteCategories(Request $request)
    {
        $data = $request->post();
        
        if (empty($data['ids']) || !is_array($data['ids'])) {
            return $this->fail('请选择要删除的类目');
        }

        try {
            $deleteCount = CategoryModel::whereIn('id', $data['ids'])->delete();

            return $this->success('批量删除成功', ['deleted_count' => $deleteCount]);
        } catch (\Exception $e) {
            return $this->fail('批量删除失败：' . $e->getMessage());
        }
    }

    /**
     * 获取类目选项（用于下拉选择）
     */
    public function getCategoryOptions(Request $request)
    {
        try {
            $categories = CategoryModel::select(['id', 'name'])
                ->orderBy('created_at', 'desc')
                ->get();

            $options = $categories->map(function ($category) {
                return [
                    'label' => $category->name,
                    'value' => $category->id
                ];
            });

            return $this->success('获取类目选项成功', $options);
        } catch (\Exception $e) {
            return $this->fail('获取类目选项失败：' . $e->getMessage());
        }
    }
}